package com.open.yujiakj.common.utils.secret;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES128Test {

    public static void main(String[] args) {
        aes128("123456789ABCDEFG", "1234567891234567");
    }


    public static byte[] aes128(String text, String key) {
        if (key == null || text == null || key.getBytes().length != 16 || text.getBytes().length != 16) {
            System.out.println("encrypt: key or text error");
            return null;
        }
        try {
            //AES128(calculate with key and text)
            Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            encCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
            byte[] encrypted = encCipher.doFinal(text.getBytes());
            for (int i = 0; i < encrypted.length; i++) {
                System.out.println( "result: " + encrypted[i]);
            }
            System.out.println(bytesToHex(encrypted));
            return encrypted;
        } catch (Exception e) {
            System.out.println(e.toString());
            return null;
        }
    }

    final protected static char[] hexArray = "0123456789abcdef".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}